package com.financing.platform.web.api;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.SMSDict;
import com.financing.platform.SMSSend;
import com.financing.platform.common.CommonConstantUtil;
import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.AccessInfoDTO;
import com.financing.platform.dto.CompanyDTO;
import com.financing.platform.dto.CorpProjectDTO;
import com.financing.platform.dto.FpProjectSeriesDTO;
import com.financing.platform.dto.FpProjectTransferHisDTO;
import com.financing.platform.dto.ProductAttachmentDTO;
import com.financing.platform.dto.ProductCheckLogDTO;
import com.financing.platform.dto.ProductRecommendDTO;
import com.financing.platform.dto.ProjectAccountDTO;
import com.financing.platform.dto.ProjectAnnualRevenueDTO;
import com.financing.platform.dto.ProjectCommentsDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.dto.ProjectExpandDTO;
import com.financing.platform.dto.ProjectRabateDTO;
import com.financing.platform.dto.ProjectRiskDTO;
import com.financing.platform.dto.SwitchDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.dto.XcxNewsDTO;
import com.financing.platform.dto.XcxSearchnoRecordDTO;
import com.financing.platform.service.ICompanyService;
import com.financing.platform.service.IFpProjectSeriesService;
import com.financing.platform.service.IFpProjectTransferHisService;
import com.financing.platform.service.IProductCheckLogService;
import com.financing.platform.service.IProductRecommendService;
import com.financing.platform.service.IProjectAccountService;
import com.financing.platform.service.IProjectAnnualRevenueService;
import com.financing.platform.service.IProjectRabateService;
import com.financing.platform.service.IProjectRiskService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.service.ISwitchService;
import com.financing.platform.service.IUserInfoService;
import com.financing.platform.service.IXcxNewsService;
import com.financing.platform.service.IXcxSearchnoRecordService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.HttpClientPostUtil;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.util.PinyinUtil;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.ProductVO;
import com.financing.platform.vo.ProjectSendConfirmEmailVO;
import com.financing.platform.vo.ProjectVO;

@Controller("projectActionApi")
@RequestMapping("/api/product")
@Scope("prototype")
public class ProjectAction extends BaseAction{

	@Autowired
	private IProjectService projectServiceImpl;

	@Autowired
	private IProjectAnnualRevenueService projectAnnualRevenueServiceImpl; 

	@Autowired
	private IProjectRabateService projectRabateSericeImpl;

	@Autowired
	private IProjectRiskService projectRiskServiceImpl;

	@Autowired
	private IProductRecommendService productRecommendServiceImpl;

	@Autowired
	private ICompanyService companyServiceImpl;

	@Autowired
	private IProjectAccountService projectAccountServiceImpl;

	@Autowired
	private IFpProjectTransferHisService fpProjectTransferHisService;

	@Autowired
	private IProductCheckLogService productCheckLogService;

	@Value("#{settings['groupId']}")
	private String groupId;

	@Value("#{settings['product_check_url']}")
	private String productCheckUrl;

	@Autowired
	private MailSenderService mailSenderService;

	@Autowired
	private IUserInfoService userInfoServiceImpl;

	@Autowired
	private ISwitchService switchSerivceImpl;

	@Autowired
	private IFpProjectSeriesService fpProjectSeriesImpl;

	@Autowired
	private IXcxSearchnoRecordService iXcxSearchnoRecordService;

	@Autowired
	private IXcxNewsService iXcxNewsService;

	ExecutorService executorService = Executors.newFixedThreadPool(10);

	@RequestMapping("/companyList.shtml")
	@ResponseBody
	public ResultMap addProjectPer(HttpServletRequest request,
			HttpServletResponse response) {

		try{
			List<CompanyDTO> companyList = 	companyServiceImpl.listCompany(null);
			resultMap.setAttribute("list", companyList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query company error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;

	}


	/**
	 * 添加产品
	 * copyType 01 表示  为复制产品及解析，需要发送邮件通知
	 * @param request
	 * @param response
	 * @param projectDTO
	 * @param corpProjectDTO
	 * @param copyType
	 * @return
	 */
	@RequestMapping("/addProject.shtml")
	@ResponseBody
	public ResultMap addProject(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO,CorpProjectDTO corpProjectDTO,String copyType) {
		try{
			projectDTO.setStatus(Dict.pProductStatus_need_Verify);
			projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
			DTOdateSet.setCreateInfo(projectDTO, request.getSession());
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());

			DTOdateSet.setCreateInfo(corpProjectDTO, request.getSession());
			DTOdateSet.setUpdateInfo(corpProjectDTO, request.getSession());

			DTOdateSet.setCreateInfo(projectExpandDTO, request.getSession());
			DTOdateSet.setUpdateInfo(projectExpandDTO, request.getSession());

			projectDTO.setpExpectSubscriptionAmount(projectDTO.getpIssuingScale());
			//将页面的万元单位换算为元 ---- 发行规模（当期）
			if(projectDTO.getpIssuingScale() != null){
				projectDTO.setpIssuingScale(projectDTO.getpIssuingScale());
			}
			//将页面的万元单位换算为元 ----- 发行总规模
			if(projectDTO.getpAllIssuingScale() != null){
				projectDTO.setpAllIssuingScale(projectDTO.getpAllIssuingScale());
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionShare(projectDTO.getpExpectSubscriptionAmount());
			}
			if(projectDTO.getpMinimumAmount() != null){
				projectDTO.setpMinimumAmount(projectDTO.getpMinimumAmount());
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionAmount(projectDTO.getpExpectSubscriptionAmount());
			}
			if(projectDTO.getpProgressiveAmount() != null){
				projectDTO.setpProgressiveAmount(projectDTO.getpProgressiveAmount());
			}

			String[]  productAttachementFileType = request.getParameterValues("fileType");
			String[]  productAttachementFileName = request.getParameterValues("fName");
			String[]  productAttachementFilePath = request.getParameterValues("fileUrl");

			List<ProductAttachmentDTO> productAttachmentDTOList = new ArrayList<ProductAttachmentDTO>() ;

			if(productAttachementFileName != null && productAttachementFileType != null && productAttachementFilePath != null && productAttachementFileName.length == productAttachementFileType.length && productAttachementFileType.length == productAttachementFilePath.length){
				for(int i = 0 ; i< productAttachementFileName.length; i++){
					ProductAttachmentDTO productAttachmentDTO = new ProductAttachmentDTO();
					productAttachmentDTO.setfName(productAttachementFileName[i]);
					productAttachmentDTO.setfUploadTime(new Date());
					productAttachmentDTO.setfType(productAttachementFileType[i]);
					productAttachmentDTO.setfPath(productAttachementFilePath[i]);
					productAttachmentDTOList.add(productAttachmentDTO);
				}
			}

			projectDTO.setpImageUri(request.getParameter("image"));

			//赋值搜索字段
			try {
				projectDTO.setpSearchName(projectDTO.getpName()+PinyinUtil.convert(projectDTO.getpName()));
			} catch (Exception e) {
				log.error("PinyinUtil.convert(projectDTO.getpName()) error!",e);
			}


			int project = projectServiceImpl.addProject(projectDTO,corpProjectDTO,productAttachmentDTOList,copyType, projectExpandDTO);
			projectDTO.setId(project);

			//变更小程序搜索记录关联状态
			{
				if(StringUtils.isNotBlank(projectDTO.getpXcxSerarnoKeyword())) {
					XcxSearchnoRecordDTO x = new XcxSearchnoRecordDTO();
					x.setKeyword(projectDTO.getpXcxSerarnoKeyword());
					x.setFeedbackStatus("1");
					iXcxSearchnoRecordService.updateByKeyword(x);
				}
			}

			resultMap.setAttribute(Dict.projectDTO, projectDTO);
			resultMap.setAttribute("projectExpandDTO", projectExpandDTO);
			resultMap.setAttribute("corpProjectDTO", corpProjectDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("add query project error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;

	}

	/**
	 * 
	 * @Title: addProjectAnnualRevenue 
	 * @Description: 添加产品年化益率和返佣
	 * @param   request
	 * @param   response
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/addProjectAnnualRevenue.shtml")
	@Transactional
	@ResponseBody
	public ResultMap addProjectAnnualRevenue(HttpServletRequest request,
			HttpServletResponse response) {

		try{

			String[] projectId = request.getParameterValues("pId");
			String[] pAnnualRevenueExpect = request.getParameterValues("pAnnualRevenueExpect");
			String[] pStartAmount = request.getParameterValues("pStartAmount");
			String[] pEndAmount =request.getParameterValues("pEndAmount");
			String[] pRabateType = request.getParameterValues("pRabateType");
			String[] pRabateProfit = request.getParameterValues("pRabateProfit");
			String[] pSellingPrice = request.getParameterValues("pSellingPrice");
			String[] pCostPrice = request.getParameterValues("pCostPrice");
			String[] pCorePrice = request.getParameterValues("pCorePrice");


			ProjectDTO project = new ProjectDTO();

			for(int i = 0;i<projectId.length; i++){

				project.setId(Integer.valueOf(projectId[i]));

				project = projectServiceImpl.queryProject(project);
				if(null == project || project.getId() == null){
					continue;
				}

				ProjectAnnualRevenueDTO projectAnnualRevenueDTO = new ProjectAnnualRevenueDTO();
				ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();

				projectAnnualRevenueDTO.setpAnnualRevenueExpect(pAnnualRevenueExpect[i]);
				projectAnnualRevenueDTO.setpStartAmount(new BigDecimal(pStartAmount[i]));
				projectAnnualRevenueDTO.setpEndAmount(new BigDecimal(pEndAmount[i]));
				projectAnnualRevenueDTO.setpId(Integer.valueOf(projectId[i]));
				if(pRabateType != null && pRabateType.length > 0){
					projectRabateDTO.setpRabateProfit(new BigDecimal(pRabateProfit[i]));
					projectRabateDTO.setpSellingPrice(new BigDecimal(pSellingPrice[i]));//销售价
					projectRabateDTO.setpCorePrice(new BigDecimal(pCorePrice[i]));//核心价
					projectRabateDTO.setpCostPrice(new BigDecimal(pCostPrice[i]));//成本价
					projectRabateDTO.setpRabateType(pRabateType[i]);
					projectRabateDTO.setpId(Integer.valueOf(projectId[i]));
					DTOdateSet.setCreateInfo(projectRabateDTO, request.getSession());
					DTOdateSet.setUpdateInfo(projectRabateDTO, request.getSession());
				}

				DTOdateSet.setCreateInfo(projectAnnualRevenueDTO, request.getSession());
				DTOdateSet.setUpdateInfo(projectAnnualRevenueDTO, request.getSession());

				int arId = projectAnnualRevenueServiceImpl.insertProjectAnnualRevenue(projectAnnualRevenueDTO);
				if(arId < 0){
					throw new Exception("add ar error!");
				}

				//arId 为-1 则年化益率插入失败
				if(pRabateType != null && pRabateType.length > 0){
					projectRabateDTO.setArId(arId);
					projectRabateSericeImpl.addProjectRabateInfo(projectRabateDTO);
				}
			}

			project.setId(Integer.valueOf(request.getParameter("id")));
			resultMap.setAttribute("project", project);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("add project AnnualRevenue error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;

	}

	@RequestMapping("/queryProjectListForPublish.shtml")
	@ResponseBody
	public ResultMap queryProjectListForPublish(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {

		try{
			log.info("Begin query project list for publish !");

			List<ProjectVO> listProjectVO = null;
			try {
				if(projectDTO.getPageNo() == null){
					projectDTO.setPageNo(1);
				}
				if(projectDTO.getPageSize() == null){
					projectDTO.setPageSize(20);
				}
				Integer count = projectServiceImpl.projectListForPublishCount(projectDTO);
				projectDTO.setTotalCount(count);
				projectDTO.setPageCount(count%projectDTO.getPageSize() == 0 ? count/projectDTO.getPageSize():count/projectDTO.getPageSize()+1);
				listProjectVO = projectServiceImpl.projectListForPublish(projectDTO);

				//查找权限转移后的产品createBy
				if(listProjectVO!= null && !listProjectVO.isEmpty()){
					FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
					for(ProjectVO projectVO : listProjectVO){
						dto.setPProjectId(projectVO.getId());
						dto.setpProjectType("01");//“01：信托，资管” 
						String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
						if(!StringUtil.isNullOrEmptyStr(createBy)){
							projectVO.setCreateBy(createBy);
						}
					}
				}
			} catch (SQLException e) {
				log.error("query product for publish  error!",e);
				listProjectVO = Collections.emptyList();
			}



			resultMap.setAttribute("projectList", listProjectVO);
			resultMap.setAttribute("projectDTO", projectDTO);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("End query project list for publish !");

		}catch(Exception e){
			log.error("query project list for publish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	@RequestMapping("/queryProjectForPublish.shtml")
	@ResponseBody
	public ResultMap queryProjectForPublish(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		try{
			ProjectDTO  project = projectServiceImpl.queryProject(projectDTO);

			ProjectCommentsDTO  projectComments = new ProjectCommentsDTO();
			projectComments.setpId(project.getId());

			//查询年化益率信息
			List<ProjectAnnualRevenueDTO> projectAnnualRevenueList = projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(project.getId());

			ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
			projectRabateDTO.setpId(project.getId());
			List<ProjectRabateDTO>  projectRabateList = projectRabateSericeImpl.queryProjectRabate(projectRabateDTO);

			//获取当前用户是否有查看核心价的权限
			UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			List<AccessInfoDTO> accessInfoList = user.getAccessList();
			boolean accessFlag = false;
			boolean b = user.getUsername().equals("方旭")||user.getUserNickname().equals("方旭")||user.getUsername().equals("李宏彪")||user.getUserNickname().equals("李宏彪");
			if(accessInfoList == null && user.getUserNickname().equals("admin")){
				accessFlag = true;
			}else if(b){
				accessFlag = true;
			}else if(accessInfoList != null ){
				//优化  提取出来 不在循环内
				boolean access = isAccess(projectDTO.getId(), request,project);
				for(AccessInfoDTO accessInfo : accessInfoList){
					if(groupId.equals(accessInfo.getGroupId()) || access){
						accessFlag = true;
						project.setTarget(1);
						break;
					}else{
						project.setTarget(0);
					}
				}
			}

			//如果没有核心价查看权限 则去掉核心价
			if(!accessFlag){
				for(ProjectRabateDTO projectRabate : projectRabateList){
					projectRabate.setpCorePrice(null);
				}
			}

			ProjectRiskDTO projectRiskDto = new ProjectRiskDTO();
			projectRiskDto.setpId(project.getId());
			List<ProjectRiskDTO> projectRiskList = projectRiskServiceImpl.queryProjectRisk(projectRiskDto);

			ProductRecommendDTO productRecommendDto = new ProductRecommendDTO();
			productRecommendDto.setFpProjectId(project.getId());

			List<ProjectAccountDTO>  projectAccountList = projectAccountServiceImpl.queryProjectAccountList(project.getId());
			Map<String,Object> projectMap = new HashMap<String,Object>();
			CorpProjectDTO corpProjectDTO = projectServiceImpl.queryCorpProject(project.getId());
			if(corpProjectDTO != null &&  corpProjectDTO.getFpCorpId() != null && 0!=corpProjectDTO.getFpCorpId() ){
				CompanyDTO companyDTO = new CompanyDTO();
				companyDTO.setId(corpProjectDTO.getFpCorpId());
				projectMap.put("projectCorpList",companyServiceImpl.listCompany(companyDTO));
			}

			//权限扭转接收人
			FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
			dto.setPProjectId(project.getId());
			dto.setpProjectType("01");//“01：信托，资管” 
			String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
			if(!StringUtil.isNullOrEmptyStr(createBy)){
				project.setCreateBy(createBy);
			}

			FpProjectSeriesDTO fpProjectSeriesDTO = new FpProjectSeriesDTO();
			List<FpProjectSeriesDTO> fpProjectSeriesList = fpProjectSeriesImpl.queryList(fpProjectSeriesDTO);

			resultMap.setAttribute("fpProjectSeriesList", fpProjectSeriesList);
			resultMap.setAttribute("project", project);
			resultMap.setAttribute("projectRiskList", projectRiskList);
			resultMap.setAttribute("projectRabateList", projectRabateList);
			resultMap.setAttribute("projectAnnualRevenueList", projectAnnualRevenueList);
			resultMap.setAttribute("projectAccountList", projectAccountList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProjectForPublish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/fpProjectSeriesList.shtml")
	@ResponseBody
	public ResultMap fpProjectSeriesList(HttpServletRequest request,
			HttpServletResponse response) {
		try{

			FpProjectSeriesDTO fpProjectSeriesDTO = new FpProjectSeriesDTO();
			List<FpProjectSeriesDTO> fpProjectSeriesList = fpProjectSeriesImpl.queryList(fpProjectSeriesDTO);

			resultMap.setAttribute("fpProjectSeriesList", fpProjectSeriesList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProjectForPublish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	/**
	 * 删除产品系列
	 * 
	 * @param request
	 * @param response
	 * @param fpProjectSeriesDTO
	 * @return
	 */
	@RequestMapping("/fpProjectSeriesDelete.shtml")
	@ResponseBody
	public ResultMap fpProjectSeriesDelete(HttpServletRequest request,
			HttpServletResponse response,FpProjectSeriesDTO fpProjectSeriesDTO) {
		try{

			if(fpProjectSeriesDTO!=null && StringUtils.isNotEmpty(fpProjectSeriesDTO.getProSeriesName())) {
				ProjectDTO p = new ProjectDTO();
				p.setpSeries(fpProjectSeriesDTO.getProSeriesName());
				List<ProjectDTO> projectList = projectServiceImpl.queryAllProject(p);

				if(projectList.size()>0) {//已引用
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_5001);
					return resultMap;
				} else {
					fpProjectSeriesImpl.deleteByProSeriesName(fpProjectSeriesDTO);

					resultMap.setStatus(STATUS.SUCCESS);
					resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
				}
			} else {
				resultMap.setStatus(STATUS.FAILE);//参数缺失
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}

		}catch(Exception e){
			log.error("queryProjectForPublish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/updateProjectForPublish.shtml")
	@ResponseBody
	public ResultMap updateProjectForPublish(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		try{

			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectServiceImpl.updateProject(projectDTO,null);

			ProjectDTO p = new ProjectDTO();
			p.setId(projectDTO.getId());
			ProjectDTO proDto= projectServiceImpl.queryProject(p);
			if(StringUtils.isNotBlank(request.getParameter("isFabu"))) {//小程序产品发布
				//变更小程序搜索记录关联状态
				XcxSearchnoRecordDTO x = new XcxSearchnoRecordDTO();
				x.setFeedbackStatus("1");//0:未引用未反馈 1：已引用 2：已反馈
				x.setKeyword(proDto.getpXcxSerarnoKeyword());
				List<XcxSearchnoRecordDTO> xcxSearchnoRecordlist = iXcxSearchnoRecordService.queryList(x);

				x.setFeedbackStatus("2");
				iXcxSearchnoRecordService.updateByKeyword(x);

				for(XcxSearchnoRecordDTO xs: xcxSearchnoRecordlist) {
					//推送消息给用户
					XcxNewsDTO xnd = new XcxNewsDTO();
					xnd.setOpenid(xs.getOpenid());
					xnd.setWxUserhearimg(xs.getWxUserhearimg());
					xnd.setWxUsername(xs.getWxUsername());
					xnd.setStatus("0");//阅读状态-未读
					xnd.setKeyWord(proDto.getpXcxSerarnoKeyword());
					xnd.setProUrl("../queryDetail/queryDetail?code="+proDto.getpCode());
					xnd.setContent("尊敬的用户，您搜索的产品关键字\'"+proDto.getpXcxSerarnoKeyword()+"\'产品已添加，敬请查看！");//内容

					DTOdateSet.setCreateInfo(xnd, request.getSession());
					DTOdateSet.setUpdateInfo(xnd, request.getSession());

					iXcxNewsService.insert(xnd);
				}
			}

			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setId(projectDTO.getId());
			final ProjectDTO pro = projectServiceImpl.queryProject(projectTmp);
			//流水记录发布成功
			Boolean flagBaoxiao = pro.getFlagBaoxiao();
			//是信托资管
			boolean isXintuo = "02,03".contains(pro.getpType());
			if((flagBaoxiao==null||!flagBaoxiao)&&isXintuo){
				if(Dict.pPublicStatus_Yes_public.equals(projectDTO.getpPublicStatus())){
					//						if(Dict.pProductStatus_need_public.equals(projectTmp.getStatus())||Dict.pProductStatus_need_public5.equals(projectTmp.getStatus())){
					String reason=StringUtils.isNotBlank(projectDTO.getCheckFirstFailReason())?projectDTO.getCheckFirstFailReason():projectDTO.getCheckFailReason();
					checkLog(projectDTO.getId(),"4","1",reason,request);
					//发布成功  给李总通知
					//单独开线程处理
					executorService.execute(new Runnable() {
						public void run() {
							//邮件短信通知产品部门领导  
							sendEmailAndSms(pro,"4");
						}
					});
					//						}
				}
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProjectForPublish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}


	@RequestMapping("/queryProjectListForVerify.shtml")
	@ResponseBody
	public ResultMap queryProjectListForVerify(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		try{
			log.info("Begin query project list for Verify !");

			projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
			projectDTO.setStatus(Dict.pProductStatus_need_Verify);
			if(projectDTO.getPageNo() == null){
				projectDTO.setPageNo(1);
			}
			if(projectDTO.getPageSize() == null){
				projectDTO.setPageSize(20);
			}
			Integer count = projectServiceImpl.projectListForPublishCount(projectDTO);
			projectDTO.setTotalCount(count);
			projectDTO.setPageCount(count%projectDTO.getPageSize() == 0 ? count/projectDTO.getPageSize():count/projectDTO.getPageSize()+1);
			List<ProjectDTO> listProjectDTO = projectServiceImpl.queryAllProject(projectDTO);

			resultMap.setAttribute("projectList", listProjectDTO);
			resultMap.setAttribute("projectDTO", projectDTO);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("End query project list for Verify !");

		}catch(Exception e){
			log.error("quer project list for verify error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/queryProjectForVerify.shtml")
	@ResponseBody
	public ResultMap queryProjectForVerify(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		try{
			projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
			projectDTO.setStatus(Dict.pProductStatus_need_Verify);
			ProjectDTO  project = projectServiceImpl.queryProject(projectDTO);

			ProjectCommentsDTO  projectComments = new ProjectCommentsDTO();
			projectComments.setpId(project.getId());


			//查询年化益率信息
			List<ProjectAnnualRevenueDTO> projectAnnualRevenueList = projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(project.getId());

			ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
			projectRabateDTO.setpId(project.getId());
			List<ProjectRabateDTO>  projectRabateList = projectRabateSericeImpl.queryProjectRabate(projectRabateDTO);

			ProjectRiskDTO projectRiskDto = new ProjectRiskDTO();
			projectRiskDto.setpId(project.getId());
			List<ProjectRiskDTO> projectRiskList = projectRiskServiceImpl.queryProjectRisk(projectRiskDto);

			List<ProjectAccountDTO>  projectAccountList = projectAccountServiceImpl.queryProjectAccountList(project.getId());


			CorpProjectDTO corpProjectDTO = projectServiceImpl.queryCorpProject(project.getId());
			if(corpProjectDTO != null &&  corpProjectDTO.getFpCorpId() != null && 0!=corpProjectDTO.getFpCorpId()){
				CompanyDTO companyDTO = new CompanyDTO();
				companyDTO.setId(corpProjectDTO.getFpCorpId());
				resultMap.setAttribute("projectCorpList",companyServiceImpl.listCompany(companyDTO));
			}

			resultMap.setAttribute("project", project);
			resultMap.setAttribute("projectRiskList", projectRiskList);
			resultMap.setAttribute("projectRabateList", projectRabateList);
			resultMap.setAttribute("projectAnnualRevenueList", projectAnnualRevenueList);
			resultMap.setAttribute("projectAccountList", projectAccountList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("project verify modify error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	/***
	 * 产品提交审核    新增或者修改费用
	 * @param request
	 * @param response
	 * @param projectDTO
	 * @return
	 */
	@RequestMapping("/projectAddCheck.shtml")
	@ResponseBody
	public ResultMap projectAddCheck(HttpServletRequest request,
			HttpServletResponse response) {
		try{
			//提交审核类型  1为新增产品审核   2为修改费用审核 
			String addCheckType=request.getParameter("addCheckType");

			String id = request.getParameter("id");
			if(StringUtil.isNullOrEmptyNStr(addCheckType,id)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			ProjectDTO projectDTO=new ProjectDTO();
			projectDTO.setId(Integer.parseInt(id));
			final ProjectDTO queryProject = projectServiceImpl.queryProject(projectDTO);
			//当前审核状态必须为 未审核
			//			   if(!"1".equals(queryProject.getStatus())){
			//				   resultMap.setStatus(STATUS.FAILE);
			//					resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
			//					return resultMap;
			//			   }
			//目前只做新增不做修改
			if(addCheckType.equals("1")){
				//
			}

			//设置提交审核时间
			projectDTO.setAddCheckTime(DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
			//状态4为提交产品部门领导审核
			projectDTO.setStatus("4");
			projectDTO.setpPublicStatus("1");

			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectServiceImpl.updateProject(projectDTO);

			//单独开线程处理
			executorService.execute(new Runnable() {
				public void run() {
					//邮件短信通知产品部门领导  
					sendEmailAndSms(queryProject,"1");
				}
			});

			//记录产品审核流水
			checkLog(projectDTO.getId(),"1","","",request);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProjectForPublish error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	/***
	 * 流水
	 * @throws SQLException
	 */
	private void checkLog(Integer id,String checkType,String checkStatus,String reason,HttpServletRequest request) throws SQLException {
		//提交审核
		ProductCheckLogDTO productCheckLog=new ProductCheckLogDTO();
		productCheckLog.setProductId(id);
		//1审核通过   2审核失败
		productCheckLog.setCheckStatus(checkStatus);
		//审核类型1.提交审核，2审核内容，3，提交发布审核，4.发布
		productCheckLog.setCheckType(checkType);
		productCheckLog.setCheckFailReason(reason);
		DTOdateSet.setCreateInfo(productCheckLog, request.getSession());
		DTOdateSet.setUpdateInfo(productCheckLog, request.getSession());
		productCheckLog.setDeleteTag("1");
		productCheckLogService.insert(productCheckLog);
	}

	/***
	 * //发送提交审核通知邮件 
	 * @param type 1发送金融产品部门领导审核通知
	 */
	public void sendEmailAndSms(ProjectDTO projectDTO,String type) {
		//
		SwitchDTO switchs = new SwitchDTO();
		switchs.setsKey("sendEmailAndSms");
		switchs = switchSerivceImpl.querySwitch(switchs);
		Map<String,Object> res = new HashMap<String,Object>();
		if(Dict.switchOn.equals(switchs.getsValue())){
			String id="";//销售部还是产品部
			//发送邮件 和 短信 
			if("1".equals(type)){
				id="productDevNoticeAuditMail";
			}else if("2".equals(type)){//销售部
				id="saleDevNoticeAuditMail";
			}else if("3".equals(type)){
				//编辑通知
				id="noticeEditMail";
			}else if("4".equals(type)){
				//发布产品通知
				id="noticeAddProductMail";
			}else{//不支持 不发送
				return ;
			}
			try {
				//查询转移
				FpProjectTransferHisDTO dto=new FpProjectTransferHisDTO();
				dto.setPProjectId(projectDTO.getId());
				dto.setpProjectType("01");//“01：信托，资管” 
				String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
				if(!StringUtil.isNullOrEmptyStr(createBy)){
					projectDTO.setCreateBy(createBy);
				}
				Map<String,Object> params = new HashMap<String,Object>();
				params.put("accessName", projectDTO.getCreateBy());
				params.put("pName", projectDTO.getpName());
				//审核地址
				params.put("httpsaddress",productCheckUrl+"/sellnum/approve.html?type="+type+"&pid="+projectDTO.getId());

				Map<String,Object> mailMap = MessageUtil.getMsgInfo("noticeAuditMailTemplate", id, params);
				//发送邮件
				MailContentDTO mail = new MailContentDTO();
				mail.setContext((String)mailMap.get(MessageUtil.KEY_CONTENT));
				mail.setRecAddress((String)mailMap.get("mailto"));
				mail.setCc((String)mailMap.get("cc"));

				//				mail.setSubject((String)mailMap.get(MessageUtil.KEY_TITLE));
				String titile="";
				if("1".equals(type)){
					//郭宗勋 新增产品【012403郭盖儿新增资管简称测试产品价格审批】，请审核
					titile=projectDTO.getCreateBy()+" 新增产品【"+projectDTO.getpName()+"】，请审核";
				}else if("2".equals(type)){
					//郭宗勋 新增产品【012403郭盖儿新增资管简称测试产品价格审批】，提交发布申请，请审核
					titile=projectDTO.getCreateBy()+" 新增产品【"+projectDTO.getpName()+"】，提交发布申请，请审核";
				}else if("4".equals(type)){
					//郭宗勋 新增产品【012403郭盖儿新增资管简称测试产品价格审批】，发布产品
					titile=projectDTO.getCreateBy()+" 新增产品【"+projectDTO.getpName()+"】，特此通知";
				}else{
					//郭宗勋 修改【012403郭盖儿新增资管简称测试产品价格审批】的价格，特此通知
					titile=projectDTO.getCreateBy()+" 修改【"+projectDTO.getpName()+"】的价格，特此通知";
				}
				mail.setSubject(titile);

				mail.setRequestTime(new Date());
				mailSenderService.send(mail);

				//发送短信
				SMSSend smsSend = new SMSSend();
				List<String>  mobileList = new ArrayList<String>();
				String phone=(String)mailMap.get("phone");
				String smscontent=(String)mailMap.get("smscontent");
				String[] split = phone.split(",");
				for (int i = 0; i < split.length; i++) {
					if(StringUtils.isBlank(split[i]))continue;
					mobileList.add(split[i]);
				}
				if(mobileList.size()>0){
					res=smsSend.sendSMS(mobileList, smscontent);
					log.info("sendMobileList:"+mobileList+" Content:"+smscontent);
				}

			} catch (Exception e) {
				log.error("send sms error!",e);
			}
		}else{
			log.info("switch is off ");
			res.put(SMSDict.result, Dict.sms_send_success);
		}
	}

	@RequestMapping("/updateProjectForVerify.shtml")
	@ResponseBody
	public ResultMap updateProjectForVerify(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {
		try{

			ProjectDTO poj=new ProjectDTO();
			poj.setId(projectDTO.getId());
			final ProjectDTO queryProject = projectServiceImpl.queryProject(poj);

			//查看该产品是否是包销   包销逻辑权限给到  金融产品部领导  并且该状态为待审核
			Boolean flagBaoxiao = queryProject.getFlagBaoxiao();
			//是信托资管
			boolean isXintuo = "02,03".contains(queryProject.getpType());
			boolean flag=true;//去除审核功能
			if((flagBaoxiao!=null&&flagBaoxiao)||!isXintuo||flag){//包销需要判断修改权限
				//判断是否有权限修改产品
				if(!isAccess(projectDTO.getId(),request,queryProject)){
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
					return resultMap;
				}
			}else{
				//金融产品领导审核通过
				if("2".equals(projectDTO.getStatus())&&"1".equals(projectDTO.getpPublicStatus())){
					//销售领导待审核   
					projectDTO.setStatus("5");
					projectDTO.setAddSaleCheckTime(DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
					String reason=StringUtils.isNotBlank(projectDTO.getCheckFirstFailReason())?projectDTO.getCheckFirstFailReason():projectDTO.getCheckFailReason();
					//产品部门领导审核通过   发送邮件和短信提醒   销售部门领导审核
					executorService.execute(new Runnable() {
						public void run() {
							//邮件短信通知产品部门领导  
							sendEmailAndSms(queryProject, "2");
						}
					});
					//记录销售审核流水
					checkLog(projectDTO.getId(),"3","1",reason,request);
				}else if("1".equals(projectDTO.getStatus())&&"4".equals(projectDTO.getpPublicStatus())){
					String reason=StringUtils.isNotBlank(projectDTO.getCheckFirstFailReason())?projectDTO.getCheckFirstFailReason():projectDTO.getCheckFailReason();
					//审核 失败  记录销售审核流水
					checkLog(projectDTO.getId(),"3","2",reason,request);
					//通知发送给金融产品   拒绝
					executorService.execute(new Runnable() {
						public void run() {
							sendRejectEmail(queryProject);
						}
					});
					//拒绝就是审核失败
					projectDTO.setStatus("6");
					//拒绝发布改成未发布
					projectDTO.setpPublicStatus("1");
				}else if("3".equals(projectDTO.getStatus())&&"2".equals(projectDTO.getpPublicStatus())){
					//销售领导审核通过
					String reason=StringUtils.isNotBlank(projectDTO.getCheckFirstFailReason())?projectDTO.getCheckFirstFailReason():projectDTO.getCheckFailReason();
					//记录销售审核流水
					checkLog(projectDTO.getId(),"4","1",reason,request);
				}
			}

			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectServiceImpl.updateProject(projectDTO,null);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update project error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	/***
	 * 拒绝发送邮件
	 * @param projectDTO
	 * @throws Exception
	 */
	private void sendRejectEmail(ProjectDTO projectDTO) {
		try {
			UserInfoDTO userInfoDTO=new UserInfoDTO();
			userInfoDTO.setUsername(projectDTO.getCreateBy());

			//查询转移
			FpProjectTransferHisDTO dto=new FpProjectTransferHisDTO();
			dto.setPProjectId(projectDTO.getId());
			dto.setpProjectType("01");//“01：信托，资管” 
			String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
			if(!StringUtil.isNullOrEmptyStr(createBy)){
				userInfoDTO.setUsername(createBy);
				projectDTO.setCreateBy(createBy);
			}
			UserInfoDTO queryUserInfo = userInfoServiceImpl.queryUserInfo(userInfoDTO);
			String telePhone = queryUserInfo.getTelePhone();
			//通知发送给金融产品   拒绝
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("accessName", projectDTO.getCreateBy());
			params.put("pName", projectDTO.getpName());
			//审核地址
			Map<String,Object> mailMap = MessageUtil.getMsgInfo("noticeAuditMailTemplate", "noticeRejectMail", params);
			//发送邮件
			MailContentDTO mail = new MailContentDTO();
			mail.setContext((String)mailMap.get(MessageUtil.KEY_CONTENT));
			mail.setRecAddress(queryUserInfo.getEmail());
			//拒绝标题拼接  郭宗勋 的【012403郭盖儿新增资管简称测试产品价格审批】，产品上架申请被拒绝，请及时查看
			String title=projectDTO.getCreateBy()+" 的【"+projectDTO.getpName()+"】，产品上架申请被拒绝，请及时查看";
			//			mail.setSubject((String)mailMap.get(MessageUtil.KEY_TITLE));
			mail.setSubject(title);

			mail.setRequestTime(new Date());
			mailSenderService.send(mail);
			//发送短信
			SMSSend smsSend = new SMSSend();
			List<String>  mobileList = new ArrayList<String>();
			String smscontent=(String)mailMap.get("smscontent");
			mobileList.add(telePhone);
			if(mobileList.size()>0)
				smsSend.sendSMS(mobileList, smscontent);
		} catch (Exception e) {
			log.error("send reject email error",e);
		}
	}

	@RequestMapping("/addProductRecommend.shtml")
	@ResponseBody
	public  ResultMap addProductRecommend(HttpServletRequest request,
			HttpServletResponse response,ProductRecommendDTO productRecommendDto) {
		try{
			productRecommendDto.setRecommendDate(new Date());
			productRecommendDto.setFaId("0");
			DTOdateSet.setCreateInfo(productRecommendDto, request.getSession());
			DTOdateSet.setUpdateInfo(productRecommendDto, request.getSession());
			productRecommendServiceImpl.addProductRecommend(productRecommendDto);

			resultMap.setAttribute("recommendleve", productRecommendDto.getRecommendWeight());
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("add productRecommend error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/productRecommendList.shtml")
	@ResponseBody
	public ResultMap productRecommendList(ProductRecommendDTO productRecommendDto){

		try{
			resultMap.setAttribute("list",productRecommendServiceImpl.queryProductRecommendList(productRecommendDto));
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query productRecommend list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);

		}

		return resultMap;
	}

	@RequestMapping("/productSet.shtml")
	@ResponseBody
	public ResultMap productSet(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO project) {
		try{
			//判断是否有权限修改产品
			if(!isAccess(project.getId(),request,null)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}

			project.setpSaleStatus(Dict.pSaleStatus_end);
			DTOdateSet.setUpdateInfo(project, request.getSession());
			projectServiceImpl.projectSet(project);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("product set  error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	/**
	 * 判断要修改的产品是否为当前用户所有
	 * @param projectId
	 * @param request
	 * @return
	 */
	private boolean isAccess(int projectId,HttpServletRequest request,ProjectDTO p){
		UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
		//超级管理员具有所有产品的管理权限
		if(user.getUsername().equals("admin")){
			return true;
		}

		//权限扭转接收人
		FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
		dto.setPProjectId(projectId);
		dto.setpProjectType("01");//“01：信托，资管” 
		String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
		if(!StringUtil.isNullOrEmptyStr(createBy)){
			//是否是扭转接收人
			if(user.getUsername().equals(createBy)){
				return true;
			}else{
				return false;
			}
		}
		if (p == null) {
			p=new ProjectDTO();
			p.setId(projectId);
			p = projectServiceImpl.queryProject(p);
		}
		if (p != null && p.getCreateBy().equals(user.getUsername())) {
			return true;
		}
		return false;
	}

	@RequestMapping("/validatoProjectCode")
	@ResponseBody
	public ResultMap validatoProjectCode(ProjectDTO project){

		try{
			List<ProjectDTO> projectList = projectServiceImpl.queryAllProject(project);

			if(projectList!= null && projectList.size()>0){
				resultMap.setAttribute(Dict.result, false);
			}else{
				resultMap.setAttribute(Dict.result, true);
			}

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("validatoprojectCode error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}

	@RequestMapping("/projectAllSubscription.shtml")
	@ResponseBody
	public  ResultMap projectAllSubscription(ProjectDTO project){
		try{
			Integer resultInt = null;
			project.setpAllSubscriptionAmount(project.getpAllSubscriptionAmount());
			resultInt = projectServiceImpl.updateAllSubscription(project);

			resultMap.setAttribute(Dict.result, resultInt);
			resultMap.setAttribute("pAllSubscriptionAmount", project.getpAllSubscriptionAmount());
			resultMap.setAttribute("pAllSubscriptionNum", project.getpAllSubscriptionNum());
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update project all subscription error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}
	/** 发送确认函
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/sendConfirmEmail.shtml")
	@ResponseBody
	public ResultMap sendConfirmEmail(HttpServletRequest request,
			HttpServletResponse response) {
		boolean success = false;
		try {
			String parmId = request.getParameter("id");
			UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			//判断参数为空
			if(StringUtil.isNullOrEmptyStr(parmId)){
				log.info("sendConfirmEmail function : projectId is null");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}

			String[] ids = parmId.split(",");
			List<Integer> pids = new ArrayList<Integer>();
			for(String id : ids){
				pids.add(Integer.parseInt(id));
			}
			//产品信息
			List<ProjectSendConfirmEmailVO> sendList = projectServiceImpl.queryProjectInfoByIds(pids.toArray(new Integer[]{}));


			// 获取邮件对象
			MailContentDTO mail = getEmailObject(sendList,user);

			success = mailSenderService.send(mail);

			//否则执行成功
			if(success){
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setMessage("邮件发送失败！");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
		} catch (Exception e) {
			log.error("sendConfirmEmail error", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}


	public MailContentDTO getEmailObject(List<ProjectSendConfirmEmailVO> sendList,UserInfoDTO user)
			throws SQLException {
		ProjectSendConfirmEmailVO beanFirst  = sendList.get(0);
		int rowspan = 0;
		ProjectSendConfirmEmailVO mailResult = null;
		ProjectSendConfirmEmailVO temp = null;
		List<Integer> tmp = new ArrayList<Integer>();
		String start = "";
		String end = "";
		// 邮件内容
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < sendList.size(); i++) {
			mailResult = sendList.get(i);
			rowspan = 0;
			for (int j = 0; j < sendList.size(); j++) {
				temp = sendList.get(j);
				if(mailResult.getPid().compareTo(temp.getPid()) == 0){
					rowspan ++;
				}
			}

			start = projectAmount(mailResult.getProjectStartAmount());
			end = projectAmount(mailResult.getProjectEndAmount());

			if(tmp.contains(mailResult.getPid())){
				sb.append(" <tr style='height: 50px;background-color:white;'>");
				sb.append("<td style='font-size:15px;'>" + start + "-" + end + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectCorePrice() + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectRabateProfit() + "</td>");
				sb.append("</tr>");
			}else{
				tmp.add(mailResult.getPid());
				sb.append(" <tr style='height: 50px;background-color:white;'>");
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + (tmp.size()) + "</td>");
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectName() + "</td>");
				sb.append("<td style='font-size:15px;'>" + start + "-" + end + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectCorePrice() + "</td>");
				sb.append("<td style='font-size:15px;'>" + mailResult.getProjectRabateProfit() + "</td>");
				//如果type为PEVC去掉大小配比
				if(!Dict.pevcProjectType.equals(mailResult.getpType())){
					sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectSizeRarioExplain() + "</td>");
				}
				sb.append("<td style='font-size:15px;' rowspan='"+rowspan+"'>" + mailResult.getProjectDueTime() + "月</td>");
				sb.append("<td rowspan='"+rowspan+"'>" + mailResult.getProjectRecruitmentSummary() + "</td>");
				sb.append("</tr>");
			}
		}
		sb.append("</table>");


		Map<String,Object> params = new HashMap<String,Object>();
		params.put("accessCompany", beanFirst.getProjectAccessCompany());
		params.put("accessName", beanFirst.getProjectAccessName());
		params.put("sysDate", DateUtil.getDate("yyyy/MM/dd"));
		params.put("loginName",user.getUsername());
		params.put("loginMobile",user.getTelePhone());
		params.put("loginEmail",user.getEmail());
		params.put("content",sb.toString());

		Map<String,Object> m  = MessageUtil.getMessageInfo("mailTemplate","sendConfirmEmail",params);
		String title = (String)m.get(MessageUtil.KEY_TITLE);
		String content = (String)m.get(MessageUtil.KEY_CONTENT);
		//如果type为PEVC去掉大小配比
		if(Dict.pevcProjectType.equals(mailResult.getpType())){
			content=content.replace("<td width=\"142\" style=\"font-size:16px;\" >大小配比</td>", "");
		}
		MailContentDTO mail = new MailContentDTO();
		mail.setContext(content);
		mail.setRecAddress(beanFirst.getProjectAccessEmail());
		mail.setCc(user.getEmail());
		mail.setSubject(title);
		mail.setRequestTime(new Date());
		return mail;
	}
	public String projectAmount(BigDecimal amount){
		if(amount != null){
			return amount.compareTo(new BigDecimal(100000000)) >= 0 ? 
					amount.divide(new BigDecimal(100000000)) + "亿" : 
						(amount.compareTo(new BigDecimal(10000)) >= 0 ? 
								amount.divide(new BigDecimal(10000)) + "万" : 
									amount).toString();
		}
		return "";
	}
	/**添加产品(修改版)
	 * copyType 01 表示  为复制产品及解析，需要发送邮件通知
	 * @param request
	 * @param response
	 * @param projectDTO 产品信息
	 * @param projectExpandDTO 产品扩展信息 
	 * @param corpProjectDTO 机构产品关联信息
	 * @param copyType
	 * @return
	 */
	@RequestMapping("/addProduct.shtml")
	@ResponseBody
	public ResultMap addProduct(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO,CorpProjectDTO corpProjectDTO,String copyType) {

		log.info("In addProduct being!");
		try{
			//赋值参数

			projectDTO.setStatus(Dict.pProductStatus_need_Verify);
			projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);

			DTOdateSet.setCreateInfo(projectDTO, request.getSession());
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());

			DTOdateSet.setCreateInfo(corpProjectDTO, request.getSession());
			DTOdateSet.setUpdateInfo(corpProjectDTO, request.getSession());

			DTOdateSet.setCreateInfo(projectExpandDTO, request.getSession());
			DTOdateSet.setUpdateInfo(projectExpandDTO, request.getSession());
			//预期销售金额 = 本期规模 （赋值）
			projectDTO.setpExpectSubscriptionAmount(projectDTO.getpIssuingScale());
			//预期销售分额 预期份额=预期认购金额/每份金额=本期规模 （赋值）
			projectDTO.setpExpectSubscriptionShare(projectDTO.getpIssuingScale());


			//赋值搜索字段
			try {
				projectDTO.setpSearchName(projectDTO.getpName()+PinyinUtil.convert(projectDTO.getpName()));
			} catch (Exception e) {
				log.error("PinyinUtil.convert(projectDTO.getpName()) error!",e);
			}

			//添加产品 service
			int project = projectServiceImpl.addProduct(projectDTO,projectExpandDTO,corpProjectDTO,copyType);
			projectDTO.setId(project);

			resultMap.setAttribute(Dict.projectDTO, projectDTO);
			resultMap.setAttribute("projectExpandDTO", projectExpandDTO);
			resultMap.setAttribute("corpProjectDTO", corpProjectDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);

			log.info("In addProduct end!");
		}catch(Exception e){
			log.error("add product error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;

	}
	/**
	 * 查询产品列表（修改版）
	 * @param request
	 * @param response
	 * @param projectDTO
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryProductList.shtml")
	@ResponseBody
	public ResultMap queryProductList(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO) {

		try{
			log.info("in queryProductList Begin!");
			List<ProjectVO> list;

			if(projectDTO.getPageNo() == null){
				projectDTO.setPageNo(1);
			}
			if(projectDTO.getPageSize() == null){
				projectDTO.setPageSize(20);
			}

			Integer count = projectServiceImpl.projectListForPublishCount(projectDTO);
			projectDTO.setTotalCount(count);
			projectDTO.setPageCount(count%projectDTO.getPageSize() == 0 ? count/projectDTO.getPageSize():count/projectDTO.getPageSize()+1);				
			if(count>0){
				list = projectServiceImpl.projectListForPublish(projectDTO);
			}else{
				list = Collections.EMPTY_LIST;
			}

			//查找权限转移后的产品createBy
			if(list!= null && !list.isEmpty()){
				FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
				for(ProjectVO projectVO : list){
					dto.setPProjectId(projectVO.getId());
					dto.setpProjectType("01");//“01：信托，资管 ,pe/vc” 
					String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
					if(!StringUtil.isNullOrEmptyStr(createBy)){
						projectVO.setCreateBy(createBy);
					}
				}
			}

			resultMap.setAttribute("list", list);
			resultMap.setAttribute("projectDTO", projectDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in queryProductList End!");
		}catch(Exception e){
			log.error("qqueryProductList!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}


	/**
	 * 查询产品列表（修改版）只给渠道部显示部分信息
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryProductQDList.shtml")
	@ResponseBody
	public ResultMap queryProductQDList(HttpServletRequest request,
			HttpServletResponse response,Pager pager) {

		try{
			log.info("in queryProductList Begin!");
			List<ProductVO> list;

			//产品列表查询参数
			Map<String,Object> params = getProductQueryParams(request);

			Integer count = projectServiceImpl.countProductListForQD(params,pager);

			pager.setTotalCount(count);
			if(count>0){
				list = projectServiceImpl.queryProductListForQD(params,pager);
			}else{
				list = Collections.EMPTY_LIST;
			}

			//查找权限转移后的产品createBy
			if(list!= null && !list.isEmpty()){
				FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
				for(ProductVO beanVO : list){
					dto.setPProjectId(beanVO.getId());
					//dto.setpProjectType("01");//“01：信托，资管 ,pe/vc”
					String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
					if(!StringUtil.isNullOrEmptyStr(createBy)){
						beanVO.setCreateBy(createBy);
					}

					beanVO.setProductLeader(beanVO.getCreateBy());

					UserInfoDTO userInfoDTO = new UserInfoDTO();
					userInfoDTO.setUsername(beanVO.getProductLeader());
					userInfoDTO = userInfoServiceImpl.queryUserInfo(userInfoDTO);
					if(userInfoDTO != null){
						beanVO.setProductLeaderMobile(userInfoDTO.getTelePhone());
					}

				}
			}

			resultMap.setAttribute("list", list);
			resultMap.setAttribute("pager", pager);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in queryProductList End!");
		}catch(Exception e){
			log.error("qqueryProductList!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	/**
	 * 查询产品详细（修改版）只给渠道部显示部分信息
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryProductQDDetail.shtml")
	@ResponseBody
	public ResultMap queryProductQDDetail(HttpServletRequest request,
			HttpServletResponse response,Integer pId) {

		try{
			log.info("in queryProductQDDetail Begin!");

			ProductVO productVO = projectServiceImpl.queryProductQDDetail(pId);

			//查找权限转移后的产品createBy
			if(productVO != null && productVO.getId() != null){

				FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
				dto.setPProjectId(productVO.getId());
				String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
				if(!StringUtil.isNullOrEmptyStr(createBy)){
					productVO.setCreateBy(createBy);
				}
				productVO.setProductLeader(productVO.getCreateBy());
				UserInfoDTO userInfoDTO = new UserInfoDTO();
				userInfoDTO.setUsername(productVO.getProductLeader());
				userInfoDTO = userInfoServiceImpl.queryUserInfo(userInfoDTO);
				if(userInfoDTO != null){
					productVO.setProductLeaderMobile(userInfoDTO.getTelePhone());
				}
			}


			resultMap.setAttribute("bean",productVO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in queryProductQDDetail End!");
		}catch(Exception e){
			log.error("queryProductQDDetail!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	/**
	 * 查询 发行机构
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryInvestOwner.shtml")
	@ResponseBody
	public ResultMap queryInvestOwner(HttpServletRequest request,
			HttpServletResponse response,String investOwnerName) {

		try{
			log.info("in queryInvestOwner Begin!");

			resultMap = new ResultMap();

			List<Map<String,Object>> list = projectServiceImpl.queryInvestOwner(investOwnerName);

			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in queryInvestOwner End!");
		}catch(Exception e){
			log.error("queryInvestOwner!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	/**
	 * 查询 小程序搜索未果记录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/searchnorecordlist.shtml")
	@ResponseBody
	public ResultMap searchnorecordlist(HttpServletRequest request,
			HttpServletResponse response) {

		try{
			log.info("in searchnorecordlist Begin!");

			resultMap = new ResultMap();

			XcxSearchnoRecordDTO xcxSearchnoRecord = new XcxSearchnoRecordDTO();
			xcxSearchnoRecord.setFeedbackStatus("0");
			List<XcxSearchnoRecordDTO> list = iXcxSearchnoRecordService.queryAllList(xcxSearchnoRecord);

			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in searchnorecordlist End!");
		}catch(Exception e){
			log.error("searchnorecordlist!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	/**
	 * 设置返佣刷选条件
	 * @param params
	 */
	private void setRabateRatio(Map<String,Object> params) {
		String rabateRatio=(String) params.get("rabateRatio");
		if("01".equals(rabateRatio)){
			//1%以下(不包含1%)	
			params.put("rabateRatioStart", "0");
			params.put("rabateRatioEnd", "1");
		}else 
			if("02".equals(rabateRatio)){
				//1%-3%(不包含3%)
				params.put("rabateRatioStart", "1");
				params.put("rabateRatioEnd", "3");
			}else 
				if("03".equals(rabateRatio)){
					//3%及以上
					params.put("rabateRatioStart", "3");
				}else
					if("04".equals(rabateRatio)){
						//不限 不添加信息
					}
	}

	/**
	 * 组装产品列表查询参数
	 * @param request
	 * @return
	 */
	private Map<String,Object> getProductQueryParams(HttpServletRequest request){

		//结款节点
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("pTypeList", request.getParameter("pTypeList"));
		params.put("pPaymentInterestType", request.getParameter("pPaymentInterestType"));//付息方式
		params.put("pInvestType", request.getParameter("pInvestType"));//投资类型
		params.put("pPublicArea", request.getParameter("pPublicArea"));//所在地区
		params.put("pBelongArea", request.getParameter("pBelongArea"));//所在地区
		params.put("pLevel", request.getParameter("pLevel"));//产品评级
		params.put("minimumAmount", request.getParameter("minimumAmount"));//起购金额
		params.put("pShortName", request.getParameter("pShortName"));//产品简称
		params.put("pSizeRatioType", request.getParameter("pSizeRatioType"));//产品简称
		params.put("saleStatus", request.getParameter("pSaleStatus")); //产品销售状态

		params.put("rabateRatio", request.getParameter("rabateRatio")); //股权基金参数  返佣比例筛选
		//股权基金参数  返佣比例筛选
		setRabateRatio(params);

		params.put("pRabateProfitParameter", request.getParameter("pRabateProfitParameter"));//返佣
		params.put("pAnnualRevenueExpectParameter", request.getParameter("pAnnualRevenueExpectParameter"));//年化率

		//添加排序方式
		getProductOrderType( request.getParameter("orderParameter"), request.getParameter("orderType"),params);

		String dueTime = request.getParameter("dueTime");//产品期限
		Map<String,Object> dueTimeMap = CommonConstantUtil.dueTimeUtils(dueTime);
		Iterator<String> dtkeySetIterator = dueTimeMap.keySet().iterator();
		while (dtkeySetIterator.hasNext()) {
			String key = dtkeySetIterator.next();
			params.put(key, dueTimeMap.get(key));
		}
		String annualRevenue = request.getParameter("annualRevenue");//收益
		Map<String,Object> annualRevenueMap = CommonConstantUtil.annualRevenueUtils(annualRevenue);
		Iterator<String>  arkeySetIterator = annualRevenueMap.keySet().iterator();
		while (arkeySetIterator.hasNext()) {
			String key = arkeySetIterator.next();
			params.put(key, annualRevenueMap.get(key));
		}
		return params;
	}

	/**
	 * 产品系列新增
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/productSeriesAdd.shtml")
	@ResponseBody
	public ResultMap productSeriesAdd(HttpServletRequest request,
			HttpServletResponse response,FpProjectSeriesDTO fpProjectSeries) {
		ResultMap resultMap = new ResultMap();
		try{
			if(fpProjectSeries!=null && StringUtils.isNotEmpty(fpProjectSeries.getProSeriesName())) {
				FpProjectSeriesDTO f = new FpProjectSeriesDTO();
				f.setProSeriesName(fpProjectSeries.getProSeriesName());
				List<FpProjectSeriesDTO> list = fpProjectSeriesImpl.queryList(f);
				if(list.size()>0) {
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_REPEAT_LOSE);
					return resultMap;
				}
				DTOdateSet.setCreateInfo(fpProjectSeries, request.getSession());
				DTOdateSet.setUpdateInfo(fpProjectSeries, request.getSession());
				fpProjectSeriesImpl.insert(fpProjectSeries);

				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			} else {
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
		} catch(Exception e) {
			log.error("productSeriesAdd!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	/**
	 * 排序方式，将参数转化成数据库参数
	 * @return
	 */
	private void  getProductOrderType(String orderParameter,String orderType,Map<String,Object> params){
		if(StringUtil.isNullOrEmptyStr(orderParameter)){
			return;
		}
		//01 投资期限	02 付息方式		03上架时间（修改时间）
		if("01".equals(orderParameter)){
			params.put("orderParameter", "P_DUE_TIME");
		}else if("02".equals(orderParameter)){
			params.put("orderParameter", "P_PAYMENT_INTEREST_TYPE");
		}else if("03".equals(orderParameter)){
			params.put("orderParameter", "CREATE_DATE");
		}


		//01 降序 02 升序
		if("01".equals(orderType)){
			params.put("orderType", "desc");
		}else if("02".equals(orderType)){
			params.put("orderType", "asc");
		}else{
			params.put("orderType", "desc");
		}

	}

}
